package com.anli1.Confog.ThreadPool;

import com.anli1.entity.pojo.Coupon;
import com.anli1.entity.pojo.CouponRedemption;
import com.anli1.entity.pojo.SyncMessage;
import com.anli1.service.ICouponRedemptionService;
import com.anli1.service.ICouponService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.Entry;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
public class getData implements Runnable {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ICouponRedemptionService iCouponRedemptionService;
    @Autowired
    private ICouponService iCouponService;


    @Override
    public void run() {
        //读取任务-加锁-免得重复读取

        //创建示例
        RedissonClient redissonClient = Redisson.create();
        //获取锁
        RLock loc=redissonClient.getLock("ying");
        try {
            boolean isLock=loc.tryLock(3, -1, TimeUnit.SECONDS);
            if (isLock) {
                //锁内执行   最大等待时间 持锁时间 分钟数
                //-2看门狗机制-只要执行完成后才会放锁
                int index = (int)(Math.random() * 10) + 1;
                String quene=String.format("ying:%s",index);
                jgtb(quene);

            }
        }catch (Exception e)
        {
            // 处理中断异常
        }finally {
            if (loc != null && loc.isLocked()) {
                loc.unlock();
            }
        }


    }
    public void jgtb(String quene)
    {///  Cursor<byte[]> couponKeys = redisTemplate.getConnectionFactory()
        // .getConnection().scan(
        // ScanOptions.scanOptions().match("*coupon*").count(100).build());
        //获取成功数据 -游标拿去

        try {
            List<String> stocks = new ArrayList<>();
            Cursor<byte[]> stocksi = redisTemplate.getConnectionFactory().
                    getConnection().scan(ScanOptions.scanOptions()
                            .match(quene).count(100).build());
            if(stocksi==null)
            {
                return;
            }
            while (stocksi.hasNext()) {
                byte[] key = stocksi.next();
                String keyStr = new String(key, StandardCharsets.UTF_8); // 转换为字符串-队列名字
                Map<String, Object> hashEntries = redisTemplate.opsForHash().entries(keyStr);//根据队列名字找key集合
                for(String key1 : hashEntries.keySet())
                {

                    stocks.add(key1);
                }
            }
            if(stocks.size()==0)
            {
                return;
            }
            for( String key:stocks)
            {
                CouponRedemption couponRedemption = new CouponRedemption();
                couponRedemption.setUserId(String.valueOf(key));
                //真是神仙代码
                Long o= (Long) redisTemplate.opsForHash().get(quene,key);
                couponRedemption.setCouponId(String.valueOf(o));
                couponRedemption.setRedemptionTime(new Date());
                couponRedemption.setStatus(1);
                iCouponRedemptionService.save(couponRedemption);
                redisTemplate.opsForHash().delete(quene,key);

                iCouponService.lambdaUpdate()
                        .setSql("available_stock = available_stock - 1")
                        .eq(Coupon::getCouponCode, o.toString()) // 确保你有合适的条件
                        .update();



            }


        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
